<template>
  <div class="realtimeSz">
    <!-- /搜索栏 -->
    <div class="search-bar">
      <div class="status-stats">
        <div class="status-item" 
          v-for="item in statusList" 
          :key="item.label"
          :class="{ active: statusValue.label === item.label }"
          :style="{ color: item.color }"
          @click="handleStatusClick(item)">
          <div v-html="item.html" class="label"></div>
          <div class="count">({{ item.count || 0 }})</div>
        </div>
      </div>

      <!-- <div class="input">
        <CustomSelect
          v-model="searchValue.vision"
          placeholder="视觉"
          :clearable="false"
          :optionList="visionList"
          @on-change="refreshTable" />
      </div> -->

      <div class="input">
        <CustomSelect
          v-model="searchValue.source"
          placeholder="来源搜索"
          :optionList="sourceList"
          @on-change="refreshTable" />
      </div>

      <div class="input">
        <CustomSelect
          v-model="searchValue.area"
          placeholder="区搜索"
          :optionList="areaList"
          @on-change="handleAreaChange" />
      </div>

      <div class="input">
        <CustomSelect
          v-model="searchValue.town"
          placeholder="镇搜索"
          :optionList="filteredTownList"
          @on-change="refreshTable" />
      </div>

      <div class="input">
        <CustomInput
          v-model="searchValue.name"
          placeholder="测站搜索"
          @on-enter="refreshTable" />
      </div>

      <div class="btn">
        <CustomButton
          type="primary"
          icon="ios-search"
          @click="refreshTable">搜索</CustomButton>
      </div>
    </div>
    <!-- /搜索栏 -->

    <!-- /表格 -->
    <div class="table-box">
      <CustomTable
        ref="JTable"
        list-url="/realtimeSz/list"
        :columns="columns"
        :isPages="false"
        :border="true"
        :search-value="searchValue"
        :height="tableHeight"
        :spanMethod="tableSpanMethod"
        @handleData="handleTableData" />
    </div>
    <!-- /表格 -->
  </div>
</template>

<script>
import { areaList, townList  } from 'common/js/modules'
import { columns, sourceList, visionList } from './js/modules'
import {gongcheng} from './js/gongcheng'
import yuan from './js/yuan'

export default {
  created () {
    this.visionList = visionList()
    this.sourceList = sourceList()
    this.areaList = areaList()
    this.townList = townList()
    this.filteredTownList = this.townList
    this.columns = columns(this)
    this.initTableHeight()
    window.addEventListener('resize', this.handleResize)
  },
  data () {
    return {
      filteredTownList: [],
      statusValue: { label: '全部' },
      searchValue: {
        isTotal: '0',
        vision: '1',
        name: '',
        area: '',
        town: '',
        source: ''
      },
      tableHeight: 600,
      originalData: [], // 存储原始数据
      filteredData: [], // 存储筛选后的数据
      statusList: [
        { html: '全部<br />数量', label: '全部', value: '全部', count: 0 },
        { html: '水情<br />正常', label: '水情正常', value: '正常', count: 0, color: '#19be6b' },
        { html: '水情<br />延迟', label: '水情延迟', value: '延迟', count: 0, color: '#ff9900'  },
        { html: '水情<br />缺失', label: '水情缺失', value: '缺失', count: 0, color: '#ed4014' },
        { html: '内江<br />缺失', label: '内江缺失', value: '缺失', count: 0, color: '#ed4014' },
        { html: '外江<br />缺失', label: '外江缺失', value: '缺失', count: 0, color: '#ed4014' },
        { html: '工情<br />正常', label: '工情正常', value: '正常', count: 0, color: '#19be6b'  },
        { html: '工情<br />缺失', label: '工情缺失', value: '缺失', count: 0, color: '#ed4014' },
        { html: '视频<br />全部在线', label: '视频全部在线', value: '全部在线', count: 0, color: '#19be6b'  },
        { html: '视频<br />部分在线', label: '视频部分在线', value: '部分在线', count: 0, color: '#ff9900' },
        { html: '视频<br />全部离线', label: '视频全部离线', value: '全部离线', count: 0, color: '#ed4014' },
        { html: '视频<br />缺失', label: '视频缺失', value: '视频缺失', count: 0, color: '#ed4014' },
      ]
    }
  },
  methods: {
    refreshTable () {
      this.$refs.JTable._getList()
    },
    handleAreaChange (value) {
      // 清空已选择的镇
      this.searchValue.town = ''
      // 根据选择的区筛选镇列表
      this.filteredTownList = value ? this.townList.filter(item => item.value.indexOf(value) > -1) : this.townList
      // 刷新表格数据
      this.refreshTable()
    },
    initTableHeight () {
      this.tableHeight = window.innerHeight - 171
    },
    tableSpanMethod (data) {
      const { row, column, rowIndex } = data;

      // 只对FACCD列进行处理（假设FACCD列的索引是0）
      if (column.key === 'faccd') {
        // 获取下一行
        const rowspanCount = this.filteredData.filter(item => item.faccd === row.faccd).length
        const sameIndex = this.filteredData.findIndex(item => item.faccd === row.faccd)
        
        if (row  && row.faccd && rowspanCount > 1 && sameIndex === rowIndex) {
          // 寻找与row.faccd相同的行，并主动合并下面对应的行数，且他是相同行的第一个
          return {
            rowspan: rowspanCount,
            colspan: 1
          }
        } else if (row  && row.faccd && rowspanCount > 1 && sameIndex < rowIndex) {
          // 寻找与row.faccd相同的行，但他不是相同行的第一个，就要被合并
          return {
          rowspan: 0,
            colspan: 0
          }
        } else {
          return {
            rowspan: 1,
            colspan: 1
          }
        }
      }
    },
    handleResize () {
      this.initTableHeight()
    },
    handleStatusClick (item) {
      this.$refs.JTable.showLoading()
      this.statusValue = item
      this.filterTableData()
    },
    filterTableData () {
      const { label, value } = this.statusValue

      switch (label) {
        case '全部':
          this.filteredData = [...this.originalData]
          break
        case '水情正常':
        case '水情延迟':
        case '水情缺失':
          this.filteredData = this.originalData.filter(item => item.wasStatus === value)
          break
        case '内江缺失':
          this.filteredData = this.originalData.filter(item => item.upzStatus === value)
          break
        case '外江缺失':
          this.filteredData = this.originalData.filter(item => item.dwzStatus === value)
          break
        case '工情正常':
        case '工情缺失':
          this.filteredData = this.originalData.filter(item => item.__custom_detailStatus === value)
          break
        case '视频全部在线':
        case '视频部分在线':
        case '视频全部离线':
        case '视频缺失':
          this.filteredData = this.originalData.filter(item => item.__custom_videoDetailStatus === value)
          break
      }

      this.$refs.JTable.tableData = this.filteredData

      this.$nextTick(() => {
        this.$refs.JTable.hideLoading()
      })

      const gongcheng2 = gongcheng.filter(item => item.STATUS == 2)
      gongcheng2.map(item => {
        const SLID = item.ID

        const obj = this.filteredData.filter(child => child.faccd === SLID)
        
        if (obj.length > 1) {
          let goodScope = -1
          let goodChild = null
          
          obj.map(child => {
            let childScope = 0
            if (child.upzStatus === '正常' && child.dwzStatus === '正常' && child.__custom_detailStatus === '正常') {
              childScope = 3
            } else if (child.upzStatus === '缺失' && child.dwzStatus === '正常' && child.__custom_detailStatus === '正常') {
              childScope = 2
            } else if (child.upzStatus === '正常' && child.dwzStatus === '缺失' && child.__custom_detailStatus === '正常') {
              childScope = 2
            }  else if (child.upzStatus === '正常' && child.dwzStatus === '正常' && child.__custom_detailStatus === '缺失') {
              childScope = 2
            } else if (child.upzStatus === '缺失' && child.dwzStatus === '缺失' && child.__custom_detailStatus === '正常') {
              childScope = 1
            } else if (child.upzStatus === '正常' && child.dwzStatus === '缺失' && child.__custom_detailStatus === '缺失') {
              childScope = 1
            } else if (child.upzStatus === '缺失' && child.dwzStatus === '正常' && child.__custom_detailStatus === '缺失') {
              childScope = 1
            } else if (child.upzStatus === '缺失' && child.dwzStatus === '缺失' && child.__custom_detailStatus === '缺失') {
              childScope = 0
            }

            if (childScope > goodScope) {
              goodScope = childScope
              goodChild = child
            }
          })

          item.__custom_cezhan = goodChild
        } else if (obj.length === 1) {
          item.__custom_cezhan = obj[0]
        }
      })

      gongcheng2.map(item => {
        const cezhanData = item.__custom_cezhan

        if (cezhanData) {
          if (cezhanData.upzStatus === '正常') {
            item['内江水位数据是否正常'] = '是'
          } else {
            item['内江水位数据是否正常'] = '否'
          } 
          if (cezhanData.dwzStatus === '正常') {
            item['外江水位数据是否正常'] = '是'
          } else {
            item['外江水位数据是否正常'] = '否'
          }

          if (cezhanData.__custom_levelStatus  === '延迟') {
            if (new Date(cezhanData.wasTm).getTime() < new Date().getTime() - 1000 * 60 * 60 * 24 * 7) {
              item['内江水位数据是否正常'] = '否'
              item['外江水位数据是否正常'] = '否'
              item['系统水情不正常原因'] = '数据延迟超过7天'
            }
          }
          if (cezhanData.__custom_levelStatus  === '缺失') {
            item['系统水情不正常原因'] = '数据缺失'
          }

          if (cezhanData.__custom_detailStatus === '正常') {
            item['闸门运行数据是否正常'] = '是'
          } else {
            item['闸门运行数据是否正常'] = '否'
            item['系统工情不正常原因'] = '数据缺失'
          }
          item['所属区'] = this.areaList.find(child => child.value === cezhanData.addvcd).label
          item['测站闸门数量'] = cezhanData.gateNum
          item['最新监测时间'] = cezhanData.wasTm
          item['数据来源'] = cezhanData.stsys
          item['系统来源'] = cezhanData.__custom_source
          item['测站编号'] = cezhanData.stcd
          item['测站名称'] = cezhanData.stnm
          if (cezhanData['__custom_detail'] && cezhanData['__custom_detail'].length) {
            item['工情最新监测时间'] = cezhanData['__custom_detail'][0]['TM']
          }

          const obj3 = yuan.find(child => child.a === cezhanData['addvcdName'] && child.c === cezhanData.stnm)
          if (obj3) {
            item['水情不正常原因'] = obj3.f
            item['水情备注'] = obj3.g
            item['工情不正常原因'] = obj3.j
            item['工情备注'] = obj3.k
            item['汇总备注'] = obj3.l
            item['海绵城市项目新建设备（新增）'] = obj3.m
          } 
        } else {
          item['所属区'] = this.areaList.find(child => child.value === item['ADDVCD']).label

          const obj3 = yuan.find(child => child.a === item['所属区'] && child.c === item['SLNM'])
          if (obj3) {
            item['水情不正常原因'] = obj3.f
            item['水情备注'] = obj3.g
            item['工情不正常原因'] = obj3.j
            item['工情备注'] = obj3.k
            item['汇总备注'] = obj3.l
            item['海绵城市项目新建设备（新增）'] = obj3.m
          }
        }
      })

      // console.log(gongcheng2)
      // console.log(JSON.stringify(gongcheng2))

      // const arr2 = gongcheng2.filter(item => item.__custom_cezhan)
      // console.log(arr2)

      // let njqs = 0
      // let wjqs = 0
      // let gqqs = 0

      // const arr = []
      // const njlist = []
      // const wjlist = []
      // const gqlist = []

      // this.filteredData.map(item => {
      //   const index = arr.findIndex(child => child === item.faccd)

      //   if (item.faccd && index === -1 && item.stsys !== '物联网平台') {
      //     const arr1 = this.filteredData.filter(child => child.faccd === item.faccd)
      //     if (arr1.length > 1) {
      //       const obj = arr1.find(child => child.upzStatus === '正常')

      //       if (!obj) {
      //         // 内江缺失
      //         njqs += 1
      //         njlist.push(...arr1)
      //       }

      //       const obj1 = arr1.find(child => child.dwzStatus === '正常')

      //       if (!obj1) {
      //         // 外江缺失
      //         wjqs += 1
      //         wjlist.push(...arr1)
      //       }

      //       const obj2 = arr1.find(child => child.__custom_detailStatus === '正常')

      //       if (!obj2) {
      //         // 工情缺失
      //         gqqs += 1
      //         gqlist.push(...arr1)
      //       }
      //     } else {
      //       if (item.upzStatus === '缺失') {
      //         // 内江缺失
      //         njqs += 1
      //         njlist.push(item)
      //       }
      //       if (item.dwzStatus === '缺失') {
      //         // 外江缺失
      //         wjqs += 1
      //         wjlist.push(item)
      //       }
      //       if (item.__custom_detailStatus === '缺失') {
      //         // 工情缺失
      //         gqqs += 1
      //         gqlist.push(item)
      //       }
      //     }

      //     arr.push(item.faccd)
      //   }
      // })

      // console.log('内江缺失', njqs)
      // console.log('外江缺失', wjqs)
      // console.log('工情缺失', gqqs)
      // console.log('内江缺失', JSON.stringify(njlist))
      // console.log('外江缺失', JSON.stringify(wjlist))
      // console.log('工情缺失', JSON.stringify(gqlist))
    },
    handleTableData (res) {
      if (res) {
        this.originalData = res.list || []
        this.filterTableData()
        
        if (res.statusCount) {
          this.statusList.forEach(item => {
            item.count = res.statusCount[item.label] || 0
          })
        }
      }
    }
  },
  beforeDestroy () {
    window.removeEventListener('resize', this.handleResize)
  }
}
</script>

<style lang="scss" scoped>
.realtimeSz {
  width: 100%;
  height: 100%;
  position: relative;
  padding-top: 10px;
  box-sizing: border-box;
  > .search-bar {
    width: 100%;
    display: flex;
    align-items: center;
    margin-bottom: 10px;
    padding: 0 10px;
    > .status-stats {
      flex: 1;
      display: flex;
      gap: 5px;
      padding: 8px 0;
      .status-item {
        cursor: pointer;
        color: #2d8cf0;
        font-size: 14px;
        transition: all 0.3s ease;
        padding: 4px 8px;
        border-radius: 4px;
        border: 1px solid transparent;
        &:hover {
          transform: translateY(-2px);
        }
        &.active {
          font-weight: bold;
          background-color: rgba(45, 140, 240, 0.1);
          border-color: currentColor;
        }
        .label {
          text-align: center;
        }
        .count {
          opacity: 0.8;
          text-align: center;
        }
      }
    }
    > .input {
      flex: 0 0 80px;
      margin-right: 5px;
    }
  }
  > .table-box {
    width: 100%;
    height: calc(100% - 42px);
    position: relative;
    padding: 0 10px;
    overflow-y: auto;
    overflow-x: hidden;
  }
}
</style>
